#!/bin/sh

prometheus_namespace() {
  echo "$CLUSTER_NAMESPACE-monitor"
}

prometheus_service() {
  echo "prometheus-kube-prometheus-prometheus"
}

install_prometheus_operator() {
  install_prometheus_operator_for_version 41.6.1 "$@"
}

install_prometheus_operator_for_version() {
  local KUBE_PROMETHEUS_STACK_VERSION="$1"
  shift

  if [ "$E2E_ENV" = "minishift" ] || [ "$E2E_ENV" = "crc" ] || [ "$E2E_ENV" = "microshift" ]
  then
    if [ "$E2E_ENV" = "minishift" ]
    then
      eval "$(minishift oc-env)"
    fi
    if [ "$E2E_ENV" = "crc" ]
    then
      eval "$(crc oc-env)"
    fi
    if [ "$E2E_ENV" = "microshift" ]
    then
      alias oc="docker exec -ti '$K8S_NAME' oc"
    fi
    kubectl create ns "$(prometheus_namespace)"
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-prometheus-oper-admission
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-prometheus-oper-operator
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-prometheus-oper-prometheus
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-kube-prometheus-admission
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-kube-prometheus-operator
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-kube-prometheus-prometheus
    oc adm policy add-scc-to-user anyuid -n "$(prometheus_namespace)" -z prometheus-grafana
  fi

  helm install prometheus "$E2E_PATH/helm/kube-prometheus-stack-$KUBE_PROMETHEUS_STACK_VERSION.tgz" \
    --create-namespace \
    --namespace "$(prometheus_namespace)" \
    --disable-openapi-validation \
    --set prometheusOperator.createCustomResource=false \
    --set alertmanager.enabled=false \
    --set kubeStateMetrics.enabled=false \
    --set nodeExporter.enabled=false \
    --set kubeDns.enabled=false \
    --set kubeProxy.enabled=false \
    --set kubeScheduler.enabled=false \
    --set coreDns.enabled=false \
    --set kubeControllerManager.enabled=false \
    --set kubeEtcd.enabled=false \
    --set-string grafana.image.tag="${E2E_GRAFANA_VERSION:-11.5.2}" \
    --set-string prometheus.prometheusSpec.podMonitorNamespaceSelector.matchLabels.monitoring=true \
    "$@"

  wait_pods_running "$(prometheus_namespace)" 3
}

uninstall_prometheus_operator() {
  helm_cleanup_chart prometheus "$(prometheus_namespace)"
  k8s_async_cleanup_namespace "$(prometheus_namespace)"
}
